document.addEventListener('DOMContentLoaded', function() {
    // DOM元素
    const announcementList = document.getElementById('announcementList');
    const announcementModal = document.getElementById('announcementModal');
    const announcementForm = document.getElementById('announcementForm');
    const createAnnouncementBtn = document.getElementById('createAnnouncementBtn');
    const closeModal = document.getElementById('closeModal');
    const cancelBtn = document.getElementById('cancelBtn');
    const modalTitle = document.getElementById('modalTitle');
    const announcementIdInput = document.getElementById('announcementId');
    const titleInput = document.getElementById('title');
    const contentInput = document.getElementById('content');
    const targetUsersSelect = document.getElementById('targetUsers');
    const logoutBtn = document.getElementById('logoutBtn');

    // 加载公告列表
    async function loadAnnouncements() {
        try {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'admin-login.html';
                return;
            }

            const response = await fetch('http://localhost:3001/api/announcements', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('获取公告列表失败');
            }

            const data = await response.json();
            renderAnnouncements(data.data);
        } catch (error) {
            console.error('加载公告失败:', error);
            announcementList.innerHTML = `<div class="error-message">加载失败: ${error.message}</div>`;
        }
    }

    // 渲染公告列表
    function renderAnnouncements(announcements) {
        if (announcements.length === 0) {
            announcementList.innerHTML = '<div class="empty-message">暂无公告数据</div>';
            return;
        }

        announcementList.innerHTML = announcements.map(announcement => `
            <div class="announcement-item">
                <div class="announcement-header">
                    <h3 class="announcement-title">${announcement.title}</h3>
                    <div class="announcement-meta">
                        ${new Date(announcement.publishDate).toLocaleString()} | 
                        发布者: ${announcement.creator ? announcement.creator.name : '系统'}
                    </div>
                </div>
                <div class="announcement-content">${announcement.content}</div>
                <div class="announcement-actions">
                    <button class="btn btn-sm btn-primary edit-btn" data-id="${announcement.id}">编辑</button>
                    <button class="btn btn-sm btn-secondary ${announcement.isActive ? 'deactivate-btn' : 'activate-btn'}" data-id="${announcement.id}">
                        ${announcement.isActive ? '停用' : '启用'}
                    </button>
                </div>
            </div>
        `).join('');

        // 添加按钮事件监听
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', () => editAnnouncement(btn.dataset.id));
        });

        document.querySelectorAll('.deactivate-btn, .activate-btn').forEach(btn => {
            btn.addEventListener('click', () => toggleAnnouncementStatus(btn.dataset.id));
        });
    }

    // 打开创建公告模态框
    function openCreateModal() {
        modalTitle.textContent = '发布新公告';
        announcementIdInput.value = '';
        titleInput.value = '';
        contentInput.value = '';
        targetUsersSelect.value = 'all';
        announcementModal.style.display = 'flex';
    }

    // 打开编辑公告模态框
    async function editAnnouncement(id) {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`http://localhost:3001/api/announcements/${id}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('获取公告详情失败');
            }

            const data = await response.json();
            const announcement = data.data;

            modalTitle.textContent = '编辑公告';
            announcementIdInput.value = announcement.id;
            titleInput.value = announcement.title;
            contentInput.value = announcement.content;
            announcementModal.style.display = 'flex';
        } catch (error) {
            console.error('编辑公告失败:', error);
            alert(`编辑公告失败: ${error.message}`);
        }
    }

    // 关闭模态框
    function closeAnnouncementModal() {
        announcementModal.style.display = 'none';
    }

    // 提交公告表单
    async function submitAnnouncementForm(e) {
        e.preventDefault();

        try {
            const token = localStorage.getItem('token');
            const id = announcementIdInput.value;
            const method = id ? 'PUT' : 'POST';
            const url = id ? `http://localhost:3001/api/announcements/${id}` : 'http://localhost:3001/api/announcements';

            const formData = {
                title: titleInput.value,
                content: contentInput.value
            };

            // 如果是新建公告，添加目标用户
            if (!id) {
                const target = targetUsersSelect.value;
                if (target !== 'all') {
                    // 获取特定角色的用户ID
                    const userResponse = await fetch(`http://localhost:3001/api/admin/users?role=${target}`, {
                        headers: {
                            'Authorization': `Bearer ${token}`
                        }
                    });
                    const userData = await userResponse.json();
                    formData.userIds = userData.data.users.map(user => user.id);
                }
            }

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                throw new Error(id ? '更新公告失败' : '发布公告失败');
            }

            closeAnnouncementModal();
            loadAnnouncements();
            alert(id ? '公告更新成功' : '公告发布成功');
        } catch (error) {
            console.error('提交公告失败:', error);
            alert(`提交公告失败: ${error.message}`);
        }
    }

    // 切换公告状态（启用/停用）
    async function toggleAnnouncementStatus(id) {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`http://localhost:3001/api/admin/announcements/${id}/status`, {
                method: 'PATCH',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('更新公告状态失败');
            }

            loadAnnouncements();
            alert('公告状态更新成功');
        } catch (error) {
            console.error('切换公告状态失败:', error);
            alert(`切换公告状态失败: ${error.message}`);
        }
    }

    // 退出登录
    function logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'admin-login.html';
    }

    // 事件监听
    createAnnouncementBtn.addEventListener('click', openCreateModal);
    closeModal.addEventListener('click', closeAnnouncementModal);
    cancelBtn.addEventListener('click', closeAnnouncementModal);
    announcementForm.addEventListener('submit', submitAnnouncementForm);
    logoutBtn.addEventListener('click', logout);

    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target === announcementModal) {
            closeAnnouncementModal();
        }
    });

    // 初始加载公告列表
    loadAnnouncements();
});